package com.budwk.app.sqfw.services.customservice.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.common.config.AppException;
import com.budwk.app.oss.services.SysOssService;
import com.budwk.app.sqfw.component.CommunityStreetComponent;
import com.budwk.app.sqfw.constants.CommonConstants;
import com.budwk.app.sqfw.constants.SqfwFormSummaryConstants;
import com.budwk.app.sqfw.models.Sqfw_cenSusPaper;
import com.budwk.app.sqfw.models.Sqfw_completeflow;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.services.SqfwCompleteflowService;
import com.budwk.app.sqfw.services.SqfwFormsummaryNewService;
import com.budwk.app.sqfw.services.common.SqfwCommonForAdminService;
import com.budwk.app.sqfw.services.common.SqfwCustomForAdminCommonService;
import com.budwk.app.sqfw.vo.CheckDataForAdminVO;
import com.budwk.app.sqfw.vo.GenerateExcelUrlVO;
import com.budwk.app.sqfw.vo.GenerateWordAndPdfUrlVO;
import com.budwk.app.sqfw.vo.SqfwCustomForAdminCommonVO;
import com.budwk.app.sqfwDoc.bo.ExcelCreateConfig;
import com.budwk.app.sqfwV2.enums.enterpriseWarrantyServe.EnterpriseWarrantyServeFileEnum;
import com.budwk.app.sqfwV2.service.enterpriseWarrantyServe.EnterpriseWarrantyServeExcelService;
import com.budwk.app.sqfwV2.service.publicSecurity.PublicSecurityService;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysLogService;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.util.adminUtils.CommonCheckUtils;
import com.budwk.app.util.poiUtils.CommonFormOfficeUtils;
import com.budwk.starter.common.page.Pagination;
import com.budwk.starter.common.result.ResultCode;
import com.budwk.starter.security.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.nutz.aop.interceptor.ioc.TransAop;
import org.nutz.dao.Cnd;
import org.nutz.dao.entity.annotation.Table;
import org.nutz.dao.sql.Criteria;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.dao.util.cri.Static;
import org.nutz.ioc.aop.Aop;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @program: dfxy-community
 * @description: 观山湖区企业包保服务（后台管理）
 * @author: LJT
 * @create: 2024-04-26 08:33
 **/
@IocBean(name = "GuanShanHuEntGuaranteeForAdminService")
@Slf4j
public class GuanShanHuEntGuaranteeForAdminServiceImpl extends EnterpriseWarrantyServeExcelService implements SqfwCustomForAdminCommonService {

    @Inject
    private CommunityStreetComponent communityStreetComponent;

    @Inject
    private SqfwFormsummaryNewService sqfwFormsummaryNewService;

    @Inject
    private SqfwCompleteflowService sqfwCompleteflowService;

    @Inject
    private SysLogService sysLogService;

    @Inject
    private SysUserService sysUserService;

    @Inject
    private PublicSecurityService publicSecurityService;

    @Inject
    private SysOssService sysOssService;

    @Inject
    private SqfwCommonForAdminService sqfwCommonForAdminService;

    @Override
    public Pagination list(SqfwCustomForAdminCommonVO bean) {
        if (StringUtils.isEmpty(bean.getType())) {
            throw new AppException(ResultCode.NOT_FOUND.getMsg());
        }
        long startTime = System.currentTimeMillis();
        // 构造查询条件
        Criteria criteria = buildQueryCond(bean);
        log.info("GuanShanHuEntGuaranteeForAdminServiceImpl-list-SQL: {}", criteria.toString());
        Pagination pagination = sqfwFormsummaryNewService.listPage(bean.getPageNo(), bean.getPageSize(), criteria);
        // 查询流程pdf
        List<Sqfw_formSummary_new> sqfwCustomForAdminCommonVOList = pagination.getList(Sqfw_formSummary_new.class);
        if (ObjectUtil.isNotEmpty(sqfwCustomForAdminCommonVOList)) {
            List<SqfwCustomForAdminCommonVO> finalCommonVOList = new ArrayList<SqfwCustomForAdminCommonVO>();
            Map<String, String> pdfUrlMap = CommonCheckUtils.getPdfUrlByFlowId(sqfwCustomForAdminCommonVOList);
            sqfwCustomForAdminCommonVOList.forEach(source -> {
                SqfwCustomForAdminCommonVO target = new SqfwCustomForAdminCommonVO();
                BeanUtil.copyProperties(source, target);
                target.setPdfUrl(pdfUrlMap.get(target.getSqfwFlowId()));
                finalCommonVOList.add(target);
            });
            pagination.setList(finalCommonVOList);
        }
        log.info("GuanShanHuEntGuaranteeForAdminServiceImpl-list-耗时: {}ms", System.currentTimeMillis() - startTime);
        return pagination;
    }

    @Override
    @Aop(TransAop.READ_COMMITTED)
    public int delete(String id) {
        Sqfw_formSummary_new sqfwFormSummaryNew = sqfwFormsummaryNewService.fetch(id);
        if (sqfwFormSummaryNew == null) {
            throw new AppException(ResultCode.NULL_DATA_ERROR.getMsg());
        }
        batchDeleteDataNew(SecurityUtil.getUserId(), sqfwFormSummaryNew);
        return 0;
    }

    @Override
    public int batchDelete(List<String> ids) {
        return sqfwCommonForAdminService.batchDelete(ids);
    }

    @Override
    public int update(Sqfw_formSummary_new sqfwFormsummaryNew) {
        return 0;
    }

    @Override
    public List<GenerateExcelUrlVO> downloadExcel(List<ExcelCreateConfig> excelConfigList, SqfwCustomForAdminCommonVO bean) {
        if (StringUtils.isEmpty(bean.getType())) {
            throw new AppException(ResultCode.NOT_FOUND.getMsg());
        }
        super.mapFileIndex.put(SecurityUtil.getUserId(), excelConfigList.get(0).getFileIdentity());
        List<GenerateExcelUrlVO> generateExcelUrlVOList = new ArrayList<GenerateExcelUrlVO>();
        GenerateExcelUrlVO generateExcelUrlVO = new GenerateExcelUrlVO();
        if (excelConfigList.get(0).getOnlyGenerateTemplateFlag()) {
            EnterpriseWarrantyServeFileEnum warrantyServeFileEnum = EnterpriseWarrantyServeFileEnum.getEnterpriseWarrantyServeFileByCode(excelConfigList.get(0).getFileIdentity());
            assert warrantyServeFileEnum != null;
            String filePath = warrantyServeFileEnum.getEmptyTemplatePath();
            String fileName = warrantyServeFileEnum.getName() + ".xlsx";
            generateExcelUrlVO.setExcelUrl(sysOssService.upload(CommonFormOfficeUtils.getTempPdfFile(filePath), fileName).getUrl());
            generateExcelUrlVOList.add(generateExcelUrlVO);
            return generateExcelUrlVOList;
        }
        // 如果formSummaryNewIdList为空，根据条件下载，否则根据勾选id下载
        if (ObjectUtil.isEmpty(bean.getFormSummaryNewIdList()) || bean.getFormSummaryNewIdList().size() <= 0) {
            Criteria criteria = buildQueryCond(bean);
            List<Sqfw_formSummary_new> summaryNewList = sqfwFormsummaryNewService.query(criteria);
            if (summaryNewList.size() > 0) {
                bean.setFormSummaryNewIdList(sqfwFormsummaryNewService.query(criteria).stream().map(Sqfw_formSummary_new::getId).collect(Collectors.toList()));
            } else {
                return new ArrayList<GenerateExcelUrlVO>();
            }
        } else {
            Cnd cnd = Cnd.NEW();
            // 时间
            if (ObjectUtil.isNotEmpty(bean.getQueryStartTime()) && ObjectUtil.isNotEmpty(bean.getQueryEndTime())) {
                cnd.and(Sqfw_formSummary_new::getFillDate, ">=", communityStreetComponent.handleStartQueryTime(bean.getQueryStartTime()));
                cnd.and(Sqfw_formSummary_new::getFillDate, "<=", communityStreetComponent.handleEndQueryTime(bean.getQueryEndTime()));
            }
            cnd.and(Sqfw_formSummary_new::getId, "IN", bean.getFormSummaryNewIdList());
            List<Sqfw_formSummary_new> summaryNewList = sqfwFormsummaryNewService.query(cnd);
            if (summaryNewList.size() > 0) {
                bean.setFormSummaryNewIdList(summaryNewList.stream().map(Sqfw_formSummary_new::getId).collect(Collectors.toList()));
            } else {
                return new ArrayList<GenerateExcelUrlVO>();
            }
        }
        return super.generateExcelForAdmin(excelConfigList, SecurityUtil.getUserId(), bean.getFormSummaryNewIdList());
    }

    @Override
    public GenerateWordAndPdfUrlVO downloadPdf
            (List<ExcelCreateConfig> excelConfigList, SqfwCustomForAdminCommonVO bean) {
        if (StringUtils.isEmpty(bean.getType())) {
            throw new AppException(ResultCode.NOT_FOUND.getMsg());
        }
        GenerateWordAndPdfUrlVO generateWordAndPdfUrlVO = new GenerateWordAndPdfUrlVO();
        if (excelConfigList.get(0).getOnlyGenerateTemplateFlag()) {
            EnterpriseWarrantyServeFileEnum warrantyServeFileEnum = EnterpriseWarrantyServeFileEnum.getEnterpriseWarrantyServeFileByCode(excelConfigList.get(0).getFileIdentity());
            assert warrantyServeFileEnum != null;
            String filePath = warrantyServeFileEnum.getEmptyTemplatePath();
            String fileName = warrantyServeFileEnum.getName() + ".docx";
            generateWordAndPdfUrlVO.setPdfUrl(sysOssService.upload(CommonFormOfficeUtils.getTempPdfFile(filePath), fileName).getUrl());
            return generateWordAndPdfUrlVO;
        }
        // 如果formSummaryNewIdList为空，根据条件下载，否则根据勾勾选id下载
        if (ObjectUtil.isEmpty(bean.getFormSummaryNewIdList()) || bean.getFormSummaryNewIdList().size() <= 0) {
            Criteria criteria = buildQueryCond(bean);
            List<Sqfw_formSummary_new> summaryNewList = sqfwFormsummaryNewService.query(criteria);
            if (summaryNewList.size() > 0) {
                bean.setFormSummaryNewIdList(summaryNewList.stream().map(Sqfw_formSummary_new::getId).collect(Collectors.toList()));
            } else {
                return new GenerateWordAndPdfUrlVO();
            }
        }
        generateWordAndPdfUrlVO.setPdfUrl(generatePdfColl(bean.getFormSummaryNewIdList()));
        return generateWordAndPdfUrlVO;
    }

    @Override
    public List<GenerateExcelUrlVO> downloadPdfList
            (List<ExcelCreateConfig> excelConfigList, SqfwCustomForAdminCommonVO bean) {
        return null;
    }

    @Override
    public Criteria buildQueryCond(SqfwCustomForAdminCommonVO bean) {
        Criteria cri = Cnd.cri();
        SqlExpressionGroup criSql = cri.where();
        if (StringUtils.isEmpty(bean.getType())) {
            throw new AppException(ResultCode.NOT_FOUND.getMsg());
        }
        // 组装查询条件
        if (StringUtils.isNotBlank(bean.getPageOrderName()) && Strings.isNotBlank(bean.getPageOrderBy())) {
            if (bean.getPageOrderBy().equals(CommonConstants.ASC)) {
                cri.getOrderBy().asc(bean.getPageOrderName());
            }
            if (bean.getPageOrderBy().equals(CommonConstants.DESC)) {
                cri.getOrderBy().desc(bean.getPageOrderName());
            }
        } else {
            cri.getOrderBy().desc(Sqfw_formSummary_new::getFillDate);
        }
        // 类型
        criSql.andEquals(SqfwCustomForAdminCommonVO::getType, bean.getType());

        Sys_user sysUser = sysUserService.fetch(SecurityUtil.getUserId());
        if (ObjectUtils.isEmpty(sysUser)) {
            throw new AppException(ResultCode.USER_NOT_FOUND.getMsg());
        }
        // 区域5级检查
        CommonCheckUtils.checkAreaRange(criSql);
        // 省
        if (StringUtils.isNotBlank(bean.getProvince()) && !CommonCheckUtils.ZHISHU.equals(bean.getProvince())) {
            criSql.andEquals(SqfwCustomForAdminCommonVO::getProvince, bean.getProvince());
        }
        // 市
        if (StringUtils.isNotBlank(bean.getCity()) && !CommonCheckUtils.ZHISHU.equals(bean.getCity())) {
            criSql.andEquals(SqfwCustomForAdminCommonVO::getCity, bean.getCity());
        }
        // 区
        if (StringUtils.isNotBlank(bean.getDistrict()) && !CommonCheckUtils.ZHISHU.equals(bean.getDistrict())) {
            criSql.andEquals(SqfwCustomForAdminCommonVO::getDistrict, bean.getDistrict());
        }
        // 街道
        if (StringUtils.isNotBlank(bean.getCounty()) && !CommonCheckUtils.ZHISHU.equals(bean.getCounty())) {
            criSql.andEquals(SqfwCustomForAdminCommonVO::getCounty, bean.getCounty());
        }
        // 时间
        if (ObjectUtil.isNotEmpty(bean.getQueryStartTime()) && ObjectUtil.isNotEmpty(bean.getQueryEndTime())) {
            criSql.andBetween(Sqfw_formSummary_new::getFillDate,
                    communityStreetComponent.handleStartQueryTime(bean.getQueryStartTime()),
                    communityStreetComponent.handleEndQueryTime(bean.getQueryEndTime()));
        }
        // 辖区
        if (StringUtils.isNotBlank(bean.getCommunity())) {
            criSql.andLike(Sqfw_formSummary_new::getCommunity, bean.getCommunity());
        }
        // 全局搜索
        if (StringUtils.isNotEmpty(bean.getQueryAll())) {
            SqlExpressionGroup businessStatus = Cnd.exps(new Static("param_data->>'businessStatus' like '%" + bean.getQueryAll() + "%'"));
            SqlExpressionGroup competentDepartment = Cnd.exps(new Static("param_data->>'competentDepartment' like '%" + bean.getQueryAll() + "%'"));
            SqlExpressionGroup enterpriseScale = Cnd.exps(new Static("param_data->>'enterpriseScale' like '%" + bean.getQueryAll() + "%'"));
            SqlExpressionGroup placeName = Cnd.exps(new Static("param_data->>'placeName' like '%" + bean.getQueryAll() + "%'"));
            SqlExpressionGroup address = Cnd.exps(new Static("param_data->>'address' like '%" + bean.getQueryAll() + "%'"));
            SqlExpressionGroup operator = Cnd.exps(new Static("param_data->>'operator' like '%" + bean.getQueryAll() + "%'"));
            SqlExpressionGroup operatorTelephone = Cnd.exps(new Static("param_data->>'operatorTelephone' like '%" + bean.getQueryAll() + "%'"));
            SqlExpressionGroup createUserName = Cnd.exps(new Static("param_data->>'createUserName' like '%" + bean.getQueryAll() + "%'"));
            SqlExpressionGroup county = Cnd.exps(new Static("county like '%" + bean.getQueryAll() + "%'"));
            SqlExpressionGroup community = Cnd.exps(new Static("community like '%" + bean.getQueryAll() + "%'"));
            criSql.and(businessStatus.or(competentDepartment).or(placeName).or(enterpriseScale).or(address).or(operator).or(operatorTelephone).or(createUserName).or(county).or(community));
        }
        // 需要排除的数据
        criSql.andNotEquals(Sqfw_formSummary_new::getFillDate, CommonConstants.WASTE_CREATE_TIME);

        // 街道
        if (StringUtils.isNotBlank(bean.getCounty())) {
            criSql.andEquals(Sqfw_formSummary_new::getCounty, bean.getCounty());
        }
        // 企业名称
        if (ObjectUtil.isNotEmpty(bean.getPlaceName())) {
            criSql.andEquals("param_data->>'placeName'", bean.getPlaceName());
        }
        // 实际经营地址
        if (ObjectUtil.isNotEmpty(bean.getAddress())) {
            criSql.andEquals("param_data->>'address'", bean.getAddress());
        }
        // 法人
        if (ObjectUtil.isNotEmpty(bean.getOperator())) {
            criSql.andEquals("param_data->>'operator'", bean.getOperator());
        }
        // 法人联系电话
        if (ObjectUtil.isNotEmpty(bean.getOperatorTelephone())) {
            criSql.andEquals("param_data->>'operatorTelephone'", bean.getOperatorTelephone());
        }
        // 经营状态
        if (StringUtils.isNotBlank(bean.getBusinessStatus())) {
            criSql.andEquals("param_data->>'businessStatus'", bean.getBusinessStatus());
        }
        // 部门
        if (StringUtils.isNotEmpty(bean.getCompetentDepartment())) {
            criSql.andLike("param_data->>'competentDepartment'", bean.getCompetentDepartment());
        }
        // 企业规模
        if (StringUtils.isNotEmpty(bean.getEnterpriseScale())) {
            criSql.andEquals("param_data->>'enterpriseScale'", bean.getEnterpriseScale());
        }
        // 企业诉求
        if (ObjectUtil.isNotEmpty(bean.getEnterpriseAppeal())) {
            criSql.andEquals("param_data->>'enterpriseAppeal'", bean.getEnterpriseAppeal());
        }
        // 检查人员
        if (ObjectUtil.isNotEmpty(bean.getCreateUserName())) {
            criSql.andEquals(Sqfw_formSummary_new::getCreateUserName, bean.getCreateUserName());
        }
        return cri;
    }

    @Override
    public List<CheckDataForAdminVO> checkDataInfoList(SqfwCustomForAdminCommonVO bean) {
        if (StringUtils.isEmpty(bean.getType())) {
            throw new AppException(ResultCode.NOT_FOUND.getMsg());
        }
        // 如果formSummaryNewIdList为空，根据条件下载，否则根据勾勾选id下载
        if (ObjectUtil.isEmpty(bean.getFormSummaryNewIdList()) || bean.getFormSummaryNewIdList().size() <= 0) {
            Criteria criteria = buildQueryCond(bean);
            List<Sqfw_formSummary_new> summaryNewList = sqfwFormsummaryNewService.query(criteria);
            if (summaryNewList.size() > 0) {
                bean.setFormSummaryNewIdList(summaryNewList.stream().map(Sqfw_formSummary_new::getId).collect(Collectors.toList()));
            }
        }

        List<CheckDataForAdminVO> checkDataForAdminVOList = new ArrayList<CheckDataForAdminVO>();
        for (EnterpriseWarrantyServeFileEnum item : EnterpriseWarrantyServeFileEnum.values()) {
            CheckDataForAdminVO checkDataForAdminVO = new CheckDataForAdminVO();
            checkDataForAdminVO.setFileIdentity(String.valueOf(item.getCode()));
            checkDataForAdminVO.setCreateConditionFlag(false);
            checkDataForAdminVO.setFileName(item.getName());
            if (item.getTemplatePath().endsWith("docx")) {
                checkDataForAdminVO.setFileName(checkDataForAdminVO.getFileName() + ".pdf");
            } else {
                checkDataForAdminVO.setFileName(checkDataForAdminVO.getFileName() + ".xlsx");
            }
            checkDataForAdminVOList.add(checkDataForAdminVO);
        }
        if (bean.getFormSummaryNewIdList().size() <= 0) {
            return checkDataForAdminVOList;
        }
        for (CheckDataForAdminVO item : checkDataForAdminVOList) {
            if (EnterpriseWarrantyServeFileEnum.ENTERPRISE_APPEAL_BOOK.getCode().equals(item.getFileIdentity())) {
                Cnd cnd = Cnd.NEW();
                cnd.and("id", "IN", bean.getFormSummaryNewIdList());
                cnd.and("type", "=", SqfwFormSummaryConstants.enterprise_warranty_serve);
                List<Sqfw_formSummary_new> formSummaryList = sqfwFormsummaryNewService.query(cnd);
                //企业诉求化解台账需要条件
                cnd.and("param_data ->>'enterpriseAppeal'", "=", String.valueOf(true));
                List<Sqfw_formSummary_new> enterpriseAppealList = sqfwFormsummaryNewService.query(cnd);
                if (enterpriseAppealList.isEmpty()) {
                    continue;
                }
                item.setCreateConditionFlag(true);
            } else {
                item.setCreateConditionFlag(true);
            }
        }
        return checkDataForAdminVOList;
    }

    @Override
    public void reGeneratePdf(String id) {
        publicSecurityService.reGeneratePDF(id);
    }

    /**
     * 生成pdf合集
     *
     * @return
     */
    private String generatePdfColl(List<String> ids) {
        List<GenerateExcelUrlVO> generateExcelUrlVOS = new ArrayList<>();
        GenerateExcelUrlVO generateExcelUrlVO = new GenerateExcelUrlVO();

        Cnd cnd = Cnd.NEW();
        cnd.and(Sqfw_formSummary_new::getType, "=", SqfwFormSummaryConstants.enterprise_warranty_serve);
        cnd.and(Sqfw_formSummary_new::getId, "in", ids);
        cnd.desc(Sqfw_formSummary_new::getFillDate);
        List<Sqfw_formSummary_new> sqfwFormSummaryNews = sqfwFormsummaryNewService.query(cnd);
        Set<String> sqfwFlowIdSet = sqfwFormSummaryNews.stream().map(Sqfw_formSummary_new::getSqfwFlowId).collect(Collectors.toSet());
        Cnd cndFlow = Cnd.where(Sqfw_completeflow::getId, "in", sqfwFlowIdSet);
        cndFlow.and(Sqfw_completeflow::getFileType, "like", "%" + SqfwFormSummaryConstants.enterprise_warranty_serve + "%")
                .and(Sqfw_completeflow::getResourcePath, "!=", "creating")
                .and(Sqfw_completeflow::getResourcePath, "!=", "error")
                .orderBy("create_date", "asc");
        List<Sqfw_completeflow> flwoList = sqfwCompleteflowService.query(cndFlow);
        String url = "";
        if (!flwoList.isEmpty()) {
            List<String> pdfPathList = flwoList.stream().map(Sqfw_completeflow::getResourcePath).collect(Collectors.toList());
            url = CommonFormOfficeUtils.createConvergePdfAndUpload(pdfPathList, EnterpriseWarrantyServeFileEnum.ENTERPRISE_INFO_PDF.getName() + DateUtil.format(new Date(), "yyyyMMddHHmmss"));
        }
        return url;
    }

    /**
     * 批量删除
     *
     * @param userId
     * @param data
     */
    private void batchDeleteDataNew(String userId, Sqfw_formSummary_new data) {
        //1 记录日志
        sysLogService.insertDelLog(userId, JSONObject.toJSONString(data), Sqfw_cenSusPaper.class.getAnnotation(Table.class).value(),
                "com.budwk.app.sqfw.services.customservice.GuanShanHuEntGuaranteeForAdminServiceImpl.batchDeleteDataNew",
                "com.budwk.app.sqfw.controllers.admin.GuanShanHuEntGuaranteeForAdminServiceImpl.batchDelete");
        // 2 删除数据
        sqfwCompleteflowService.deleteAndUpdateWO(data.getSqfwFlowId());
    }
}
